import { makeAutoObservable } from 'mobx';
import { Menu,MenuFormValues} from './menuTypes';
import { getMenuList, createMenu, updateMenu, getInfo, deleteMenu } from '../../../../../apis/backhub/menu';

class MenuStore {
  menus: Menu[] = [];
  modalVisible = false; // 弹窗显示状态
  editingMenu: Menu | undefined = undefined; // 当前编辑的菜单，undefined表示新建
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取菜单列表
  fetchMenus = async () => {
    this.loading = true;
    try {
      const response = await getMenuList();
      this.menus = (response as any).data;
    } catch (error) {
      console.error('获取菜单列表失败:', error);
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingMenu = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (func: Menu) => {
    this.editingMenu = func;
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingMenu = undefined;
  };

  // 保存菜单
  saveMenu = async (values: MenuFormValues) => {
    try {
      if (this.editingMenu && this.editingMenu.id) {
        await updateMenu(this.editingMenu.id, values);
      } else {
        await createMenu(values);
      }
      this.hideModal();
      this.fetchMenus();
    } catch (error) {
      console.error('保存菜单失败:', error);
    }
  };

  // 获取菜单
  getMenu = async (id: string) => {
    try {
      this.loading = true;
      const response = await getInfo(id);
      this.editingMenu =  (response as any).data;
      return this.editingMenu; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 删除菜单
  deleteMenu = async (id: string) => {
    try {
      await deleteMenu(id);
      this.fetchMenus();
    } catch (error) {
      console.error('删除菜单失败:', error);
    }
  };
}

export const menuStore = new MenuStore();